import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, Form, Input, InputNumber, Button, Radio, Space, message } from 'antd';
import { UserOutlined, TeamOutlined } from '@ant-design/icons';
import { createStudent, createTeacher } from '../../api/admin';

type UserRole = 'student' | 'teacher';

export default function AddUser() {
  const queryClient = useQueryClient();
  const [role, setRole] = useState<UserRole>('student');
  const [form] = Form.useForm();
  const [success, setSuccess] = useState(false);

  const createStudentMutation = useMutation({
    mutationFn: createStudent,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'students'] });
      message.success('学生信息添加成功');
      setSuccess(true);
      setTimeout(() => {
        setSuccess(false);
        form.resetFields();
        setRole('student');
      }, 3000);
    },
    onError: (error: any) => {
      message.error(error.message || '添加失败，请重试');
    },
  });

  const createTeacherMutation = useMutation({
    mutationFn: createTeacher,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'teachers'] });
      message.success('教师信息添加成功');
      setSuccess(true);
      setTimeout(() => {
        setSuccess(false);
        form.resetFields();
        setRole('student');
      }, 3000);
    },
    onError: (error: any) => {
      message.error(error.message || '添加失败，请重试');
    },
  });

  const handleRoleChange = (e: any) => {
    const newRole = e.target.value;
    setRole(newRole);
    form.resetFields();
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (role === 'student') {
        // 创建学生 - 根据后端AddStudentsRequest需要：username, password, name, studentNo, college, major, clazz
        // 数据库Students表有：studentNo, major, clazz, grade
        const studentData = {
          username: values.studentNo, // 使用学号作为用户名
          password: '123456', // 默认密码
          name: values.name,
          studentNo: values.studentNo,
          college: values.college,
          major: values.major,
          clazz: values.clazz,
          // grade字段数据库表有，虽然后端代码暂时注释了，但先发送以便将来支持
        };
        createStudentMutation.mutate(studentData);
      } else {
        // 创建教师 - 根据后端AddTeachersRequest需要：username, password, name, account, college, title
        const teacherData = {
          username: values.account, // 使用工号作为用户名
          password: '123456', // 默认密码
          name: values.name,
          account: values.account,
          college: values.college,
          title: values.title,
        };
        createTeacherMutation.mutate(teacherData);
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  if (success) {
    return (
      <div className="p-4 pb-24 flex items-center justify-center min-h-screen">
        <Card className="text-center" style={{ maxWidth: 500 }}>
          <div className="text-6xl mb-4">✅</div>
          <div className="text-xl font-semibold text-green-600 mb-2">
            {role === 'student' ? '学生' : '教师'}信息添加成功
          </div>
          <div className="text-gray-500">页面将在3秒后自动刷新...</div>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-4 pb-24 flex justify-center">
      <div className="w-full max-w-3xl">
        <Card className="shadow-md">
          <div className="text-xl font-semibold mb-6 text-gray-800">添加用户</div>
          
          {/* 角色选择 */}
          <div className="mb-6">
            <div className="text-sm text-gray-600 mb-3">选择用户角色</div>
            <Radio.Group 
              value={role} 
              onChange={handleRoleChange}
              className="w-full"
              size="large"
            >
              <Space className="w-full" size="large">
                <Radio.Button 
                  value="student" 
                  className="flex-1 text-center hover:scale-105 transition-all duration-300"
                  style={{ 
                    height: 60,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <UserOutlined className="mr-2 text-lg" />
                  添加学生
                </Radio.Button>
                <Radio.Button 
                  value="teacher" 
                  className="flex-1 text-center hover:scale-105 transition-all duration-300"
                  style={{ 
                    height: 60,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <TeamOutlined className="mr-2 text-lg" />
                  添加教师
                </Radio.Button>
              </Space>
            </Radio.Group>
          </div>

          {/* 表单 */}
          <div 
            key={role}
            className="transition-all duration-500 ease-in-out"
            style={{
              animation: 'fadeIn 0.5s ease-in-out'
            }}
          >
            <style>{`
              @keyframes fadeIn {
                from {
                  opacity: 0;
                  transform: translateY(-10px);
                }
                to {
                  opacity: 1;
                  transform: translateY(0);
                }
              }
            `}</style>
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
            >
            {role === 'student' ? (
              <>
                {/* 学生表单 */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <Form.Item
                    label="姓名"
                    name="name"
                    rules={[{ required: true, message: '请输入姓名' }]}
                  >
                    <Input placeholder="请输入姓名" />
                  </Form.Item>
                  
                  <Form.Item
                    label="学号"
                    name="studentNo"
                    rules={[
                      { required: true, message: '请输入学号' },
                      { pattern: /^\d+$/, message: '学号只能包含数字' }
                    ]}
                  >
                    <Input placeholder="请输入学号" />
                  </Form.Item>
                  
                  <Form.Item
                    label="所属学院"
                    name="college"
                    rules={[{ required: true, message: '请输入所属学院' }]}
                  >
                    <Input placeholder="请输入所属学院" />
                  </Form.Item>
                  
                  <Form.Item
                    label="专业"
                    name="major"
                    rules={[{ required: true, message: '请输入专业' }]}
                  >
                    <Input placeholder="请输入专业" />
                  </Form.Item>
                  
                  <Form.Item
                    label="年级"
                    name="grade"
                    rules={[{ required: true, message: '请输入年级' }]}
                  >
                    <Input placeholder="例如：2021级" />
                  </Form.Item>
                  
                  <Form.Item
                    label="班级"
                    name="clazz"
                    rules={[{ required: true, message: '请输入班级' }]}
                  >
                    <Input placeholder="例如：软件2101班" />
                  </Form.Item>
                  
                  <Form.Item
                    label="邮箱"
                    name="email"
                    rules={[
                      { type: 'email', message: '请输入有效的邮箱地址' }
                    ]}
                  >
                    <Input placeholder="请输入邮箱（可选）" />
                  </Form.Item>
                  
                  <Form.Item
                    label="联系电话"
                    name="phone"
                    rules={[
                      { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
                    ]}
                  >
                    <Input placeholder="请输入联系电话（可选）" />
                  </Form.Item>
                </div>
              </>
            ) : (
              <>
                {/* 教师表单 */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <Form.Item
                    label="姓名"
                    name="name"
                    rules={[{ required: true, message: '请输入姓名' }]}
                  >
                    <Input placeholder="请输入姓名" />
                  </Form.Item>
                  
                  <Form.Item
                    label="工号"
                    name="account"
                    rules={[
                      { required: true, message: '请输入工号' }
                    ]}
                  >
                    <Input placeholder="请输入工号" />
                  </Form.Item>
                  
                  <Form.Item
                    label="所属学院"
                    name="college"
                    rules={[{ required: true, message: '请输入所属学院' }]}
                  >
                    <Input placeholder="请输入所属学院" />
                  </Form.Item>
                  
                  <Form.Item
                    label="职称"
                    name="title"
                    rules={[{ required: true, message: '请输入职称' }]}
                  >
                    <Input placeholder="例如：教授、副教授、讲师" />
                  </Form.Item>
                  
                  <Form.Item
                    label="邮箱"
                    name="email"
                    rules={[
                      { type: 'email', message: '请输入有效的邮箱地址' }
                    ]}
                  >
                    <Input placeholder="请输入邮箱（可选）" />
                  </Form.Item>
                  
                  <Form.Item
                    label="联系电话"
                    name="phone"
                    rules={[
                      { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
                    ]}
                  >
                    <Input placeholder="请输入联系电话（可选）" />
                  </Form.Item>
                  
                  <Form.Item
                    label="研究方向"
                    name="researchArea"
                    className="md:col-span-2"
                  >
                    <Input.TextArea 
                      placeholder="请输入研究方向（可选）"
                      rows={3}
                      showCount
                      maxLength={200}
                    />
                  </Form.Item>
                  
                  <Form.Item
                    label="发表论文数"
                    name="publishedPapers"
                    rules={[
                      { type: 'number', min: 0, message: '论文数不能为负数' }
                    ]}
                  >
                    <InputNumber 
                      placeholder="请输入发表论文数（可选）"
                      min={0}
                      className="w-full"
                      style={{ width: '100%' }}
                    />
                  </Form.Item>
                </div>
              </>
            )}
            
            <Form.Item className="mt-6">
              <div className="flex justify-end">
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  size="large"
                  loading={createStudentMutation.isPending || createTeacherMutation.isPending}
                  style={{ minWidth: 120 }}
                >
                  创建{role === 'student' ? '学生' : '教师'}
                </Button>
              </div>
            </Form.Item>
          </Form>
          </div>
        </Card>
      </div>
    </div>
  );
}

